import axios from 'axios';
import { getUserAgent } from '../utils/crawlerUtils';
import fs from 'fs';
import path from 'path';
import { app } from 'electron';
import { HttpsProxyAgent } from 'https-proxy-agent';
axios.defaults.maxRedirects = 0;

const RESOURCES_PATH = app && app.isPackaged
    ? path.join(process.resourcesPath, '')
    : path.join(__dirname, '../../');

const validateStatus = (status: number) => {
    return status >= 200 && status <= 303; // 默认的范围是 200-299，这里我们把302也视为正常
}

class CommentHelper {
    _userAgent: string;
    _cookieStr: string = '';
    _ip: any;
    constructor() {
        this._userAgent = getUserAgent();
    }
    async init(user: { userId: string }, ip?: string){
        this._ip = ip;
        await this.initCookies(user.userId);
    }

    async initCookies(userId: string) {
        const passToken = fs.readFileSync(`${RESOURCES_PATH}/userData/${userId}`, 'utf-8');
        const time = Date.now();
        const url = `https://id.kuaishou.com/pass/kuaishou/login/passToken?callback=https%3A%2F%2Fwww.kuaishou.com%2Frest%2Finfra%2Fsts%3FfollowUrl%3Dhttps%253A%252F%252Fpassport.kuaishou.com%252Fpc%252Faccount%252FpassToken%252Fresult%253Fsuccessful%253Dtrue%2526id%253DSSO_${time}%2526for%253DpassTokenSuccess%26failUrl%3Dhttps%253A%252F%252Fpassport.kuaishou.com%252Fpc%252Faccount%252FpassToken%252Fresult%253Fsuccessful%253Dfalse%2526id%253DSSO_${time}%2526for%253DpassTokenSuccess%26setRootDomain%3Dfalse&__loginPage=https%3A%2F%2Fpassport.kuaishou.com%2Fpc%2Faccount%2FpassToken%2Fresult%3Fsuccessful%3Dfalse%26id%3DSSO_${time}%26for%3DpullTokenFail&sid=kuaishou.server.web`
        const Cookie = `userId=${userId}; passToken=${passToken}`;
        const headers = {
            "User-Agent": this._userAgent,
            Cookie
        };
        const res = await axios.get(url, { headers, validateStatus });
        const res2 = await axios.get(res.headers.location, { headers, validateStatus });
        const cookies = res2.headers['set-cookie'] || [];
        const cookieStr = cookies.map(item => item.split(';')[0]).join('; ');
        this._cookieStr = cookieStr;
    }

    async initCookies2(userId: string, passToken: string) {
        // const passToken = fs.readFileSync(`${RESOURCES_PATH}/userData/${userId}`, 'utf-8');
        const time = Date.now();
        const url = `https://id.kuaishou.com/pass/kuaishou/login/passToken?callback=https%3A%2F%2Fwww.kuaishou.com%2Frest%2Finfra%2Fsts%3FfollowUrl%3Dhttps%253A%252F%252Fpassport.kuaishou.com%252Fpc%252Faccount%252FpassToken%252Fresult%253Fsuccessful%253Dtrue%2526id%253DSSO_${time}%2526for%253DpassTokenSuccess%26failUrl%3Dhttps%253A%252F%252Fpassport.kuaishou.com%252Fpc%252Faccount%252FpassToken%252Fresult%253Fsuccessful%253Dfalse%2526id%253DSSO_${time}%2526for%253DpassTokenSuccess%26setRootDomain%3Dfalse&__loginPage=https%3A%2F%2Fpassport.kuaishou.com%2Fpc%2Faccount%2FpassToken%2Fresult%3Fsuccessful%3Dfalse%26id%3DSSO_${time}%26for%3DpullTokenFail&sid=kuaishou.server.web`
        const Cookie = `userId=${userId}; passToken=${passToken}`;
        const headers = {
            "User-Agent": this._userAgent,
            Cookie
        };
        const config: any = { headers, validateStatus };
        if (this._ip) {
            const httpsAgent = new HttpsProxyAgent(`http://${this._ip.ip}:${this._ip.port}`);
            config.httpsAgent = httpsAgent;
        }

        const res = await axios.get(url, config);
        const res2 = await axios.get(res.headers.location, config);
        const cookies = res2.headers['set-cookie'] || [];
        const cookieStr = cookies.map(item => item.split(';')[0]).join('; ');
        this._cookieStr = cookieStr;
    }

    async getOwnerInfo(photoId: string) {

        const url = `https://www.kuaishou.com/short-video/${photoId}`;
    
        const headers = {
            "User-Agent": this._userAgent,
            Cookie: this._cookieStr
        };
    
        const res = await axios.get(url, { headers });
        const str = res.data;
        let regex = /"expTag":"([^"]*)"/; // 正则表达式匹配 "expTag":"任意字符，直到遇到另一个双引号"
        let match = regex.exec(str); // 执行匹配操作
        let expTag ='';
        if (match?.length) {
            expTag = match[1];
        }
        let photoAuthorId ='';
        regex = /"VisionVideoDetailAuthor:([^"]*)"/; // 正则表达式匹配 "expTag":"任意字符，直到遇到另一个双引号"
        match = regex.exec(str); // 执行匹配操作
        if (match?.length) {
            photoAuthorId = match[1];
        }
    
        return {
            expTag: expTag.replace('\\u002F', '/'),
            photoAuthorId
        };
    }

    async commentWorks(photoId: string, commentStr: string): Promise<boolean> {
        const ownerInfo = await this.getOwnerInfo(photoId);
        const url = 'https://www.kuaishou.com/graphql';

        const headers = {
            "User-Agent": this._userAgent,
            Cookie: this._cookieStr
        };
        
        const data = {
            operationName: "visionAddComment",
            variables: {
                photoId,
                photoAuthorId: ownerInfo.photoAuthorId,
                content: commentStr,
                expTag: ownerInfo.expTag
            },
            "query": "mutation visionAddComment($photoId: String, $photoAuthorId: String, $content: String, $replyToCommentId: ID, $replyTo: ID, $expTag: String) {\n  visionAddComment(photoId: $photoId, photoAuthorId: $photoAuthorId, content: $content, replyToCommentId: $replyToCommentId, replyTo: $replyTo, expTag: $expTag) {\n    result\n    commentId\n    content\n    timestamp\n    status\n    __typename\n  }\n}\n"
        };

        const config: any = { headers };
        if (this._ip) {
            const httpsAgent = new HttpsProxyAgent(`http://${this._ip.ip}:${this._ip.port}`);
            config.httpsAgent = httpsAgent;
        }

        try {
            const res = await axios.post(url, data, config);
            if (res.data.data.visionAddComment.status === 'success') {
                return true;
            } else {
                console.log(res.data)
                // Logger.info('')
            }  
        } catch (error) {
            console.log(error)
        }
        return false;
    }
}

export default CommentHelper;